import hashlib
import json
import logging
import random

import requests
import sys

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler1 = logging.FileHandler('proxy.py.log')
handler1.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler1.setFormatter(formatter)
logger.addHandler(handler1)

handler2 = logging.StreamHandler()
handler2.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler2.setFormatter(formatter)
logger.addHandler(handler2)

_juliang_pool = []
_juliang_current = None

status_started = "started"
status_success = "success"


class JuLiang(object):
    user = None
    pwd = None
    trade_no = None
    api_key = None
    api_url = None
    status = status_started

    def __init__(self, user, pwd, trade_no, api_key, api_url):
        self.user = user
        self.pwd = pwd
        self.trade_no = trade_no
        self.api_key = api_key
        self.api_url = api_url
        self.status = status_started


def juliang_user_pool():
    global _juliang_pool
    global _juliang_current
    if not _juliang_pool:
        _user_name = "18841866743"
        _pass_word = "wsVIsEEo"
        _trade_no = 1504136887051135
        _api_key = "374bfc8a05784bc08b06ab9f71ca821c"
        _api_url = "http://v2.api.juliangip.com/dynamic/getips?auto_white=1&num=1&pt=1&result_type=text&split=1&trade_no=1504136887051135&sign=ee063e318a9333b53a20fa93bdef2ee0"
        _juliang_pool.append(JuLiang(_user_name, _pass_word, _trade_no, _api_key, _api_url))

        _user_name = "18600951201"
        _pass_word = "bpX3BNaM"
        _trade_no = 1541630497345645
        _api_key = "88658e1e01a74ebab60dc20a028924ea"
        _api_url = "http://v2.api.juliangip.com/dynamic/getips?auto_white=1&num=1&pt=1&result_type=text&split=1&trade_no=1541630497345645&sign=9f5877bf93652e547684610fe5c78423"
        _juliang_pool.append(JuLiang(_user_name, _pass_word, _trade_no, _api_key, _api_url))

        _user_name = "15313969026"
        _pass_word = "i9EcCsqU"
        _trade_no = 1643790889309016
        _api_key = "e0831af20e224204b4ea6f3ef71cc35f"
        _api_url = "http://v2.api.juliangip.com/dynamic/getips?auto_white=1&num=1&pt=1&result_type=text&split=1&trade_no=1643790889309016&sign=9809eb0f16262d52cc8f8e5884a0ed8c"
        _juliang_pool.append(JuLiang(_user_name, _pass_word, _trade_no, _api_key, _api_url))

        _juliang_current = _juliang_pool[0]


def next_juliang():
    global _juliang_pool
    global _juliang_current
    if _juliang_current.status == status_success:
        find = False
        for juliang in _juliang_pool:
            if juliang.trade_no != _juliang_current.trade_no and juliang.status==status_started:
                logger.info("切换%s至%s" % (_juliang_current.user, juliang.user))
                _juliang_current = juliang
                find = True
                break
        if not find:
            sys.exit("所有用户的ip可能都已用完,系统退出")


def check(proxy_ip):
    global _juliang_current
    url = "http://v2.api.juliangip.com/dynamic/check"
    trade_no = _juliang_current.trade_no
    key = _juliang_current.api_key
    query_lst = ["proxy=%s" % proxy_ip, "trade_no=%s" % trade_no]
    query_lst.sort()
    query_lst.append("key=%s" % key)
    query_str = "&".join(query_lst)

    md5_hash = hashlib.md5()
    md5_hash.update(query_str.encode("utf-8"))
    hex_dig = md5_hash.hexdigest()

    try:
        resp = requests.get("%s?%s&sign=%s" % (url, query_str, hex_dig))
        resp_d = json.loads(resp.text)
        return resp_d.get("data").get(proxy_ip)
    except Exception as e:
        logger.error(e)


proxy_pool = []


def newIp():
    global _juliang_current
    # api_url = "http://v2.api.juliangip.com/dynamic/getips?auto_white=1&num=1&pt=1&result_type=text&split=1&trade_no=1541630497345645&sign=9f5877bf93652e547684610fe5c78423"
    proxy_ip = requests.get(_juliang_current.api_url).text
    return proxy_ip


def proxyIp():
    if proxy_pool:
        proxy_ip = proxy_pool[0]
        if not check(proxy_ip):
            proxy_ip = newIp()
            proxy_pool[0] = proxy_ip
    else:
        proxy_ip = newIp()
        proxy_pool.append(proxy_ip)
    return proxy_ip


def request(url):
    juliang_user_pool()
    proxy_ip = proxyIp()
    username = _juliang_current.user
    password = _juliang_current.pwd

    proxies = {
        "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": proxy_ip},
        "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": proxy_ip},
    }

    user_agents = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36'
    ]

    target_url = url

    headers = {"User-Agent": random.choice(user_agents)}
    try:
        # 使用代理IP发送请求
        response = requests.get(target_url, proxies=proxies, headers=headers, timeout=50)
        logger.info("%s,%s,%s" % (response.status_code, url, proxy_pool))
        if response.status_code == 200:
            return response.text
    except requests.exceptions.InvalidURL as e:
        process_exception(url, proxy_pool, e)
    except Exception as e:
        logger.error("%s,%s,%s" % (url, proxy_pool, e))


NOT_FIND = -1


def process_exception(url, proxy_pool, e):
    global _juliang_current
    logger.error("%s,%s,%s" % (url, proxy_pool, e))
    msg = str(proxy_pool)
    # msg = """['{"code":405,"msg":"业务已到期，请先续费订单或者重新下单","data":null}']"""
    if msg.find("业务已到期") != NOT_FIND:
        logger.error("业务已到期,系统退出,%s" % _juliang_current.user)
        sys.exit(-1)
    elif msg.find("不在白名单列表中") != NOT_FIND:
        logger.error("不在白名单列表中,继续处理,%s" % _juliang_current.user)
        sys.exit(-1)
    elif msg.find("当前业务无可用余量") != NOT_FIND:
        logger.error("当前业务无可用余量,%s" % _juliang_current.user)
        _juliang_current.status = status_success
        next_juliang()
        # sys.exit(-1)


if __name__ == "__main__":
    # c = check("49.79.133.4:46629")
    # print(c)

    url = "https://guba.eastmoney.com/list,000625,f.html"
    request(url)
    # request("https://www.baidu.com")
    # print(newIp())
